React localhost向Laravel php api 發送一個請求以檢索 json 數據,但得到上述錯誤
解法建議:
安裝 fruitcake/laravel‑cors 的套件並依照說明創建middleware
數值雖然有取回,但無法設置資料狀態
import React, { Component } from 'react'
import axios from 'axios'
class Admin extends Component {
constructor(props) {
super(props)
this.state = {
users: []
}
}
componentDidMount(){
axios.get('/api/adminUsers')
.then(response =>{
this.setState({users: response.data})
console.log(response.data)
console.log(this.setState({users: response.data}))
})
.catch(error=>{
this.setState({ errorMsg: "Something is wrong here"})
console.log(error)
})
}
render() {
const{users} = this.state
<div>
{
users.length ?
users.map(user => <div key=
{user.id}>{user.name}</div>)
: null
}
</div>
)
}
}
export default Admin
The code seems fine below is a fully working example:
import React from "react";
import ReactDOM from "react‑dom";
class Admin extends React.Component {
constructor(props) {
super(props)
this.state = {
users: [],
errorMsg: ''
}
}
componentDidMount() {
axios.get('/api/adminUsers')
.then(response => {
this.setState({users: response.data.users})
console.log(response.data)
})
.catch(error => {
this.setState({errorMsg: "Something is wrong here"})
console.log(error)
})
}
render() {
const {users, errorMsg} = this.state;
return <div>
{users.length ? users.map(user => <div key={user.id}>{user.name}</div>) : null}
{errorMsg ? <div>{errorMsg}</div> : null}
</div>
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Admin/>, rootElement);